<?php

namespace src\database\connectors;


use src\interfaces\IConnectorInterface;

class MySqlConnector extends Connector implements IConnectorInterface
{
    public function connect(array $config)
    {
        $dsn = $this->getDsn($config);
        $options = $this->getOptions($config);
        $pdo = $this->createConnection($dsn, $config, $options);

        $this->setDatabase($pdo, $config);
        $this->setTimezone($pdo, $config);
        $this->setChar($pdo, $config);

        return $pdo;
    }

    protected function setDatabase($connection, array $config)
    {
        if (! empty($config['database'])) {
            $connection->exec("use `{$config['database']}`;");
        }
    }

    protected function setTimezone($connection, array $config)
    {
        if (isset($config['timezone'])) {
            $connection->prepare('set time_zone="'.$config['timezone'].'"')->execute();
        }
    }

    protected function setChar($connection, array $config)
    {
        if (! isset($config['charset'])) {
            return $connection;
        }
        $connection->prepare(
            "set names '{$config['charset']}'".$this->getCollation($config)
        )->execute();
    }

    protected function getCollation(array $config)
    {
        return isset($config['collation']) ? " collate '{$config['collation']}'" : '';
    }

    protected function getDsn($config)
    {
        if (isset($config['unix_socket']) && ! empty($config['unix_socket'])){
            return "mysql:unix_socket={$config['unix_socket']};dbname={$config['database']}";
        }else{
            extract($config, EXTR_SKIP);
            return isset($port)
                ? "mysql:host={$host};port={$port};dbname={$database}"
                : "mysql:host={$host};dbname={$database}";
        }
    }

    protected function getOptions($config)
    {
        $options = $config['options'] ?? [];
        return array_diff_key($this->options, $options) + $options;
    }
}